package cmcshan1;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class AdministratorSqlView extends JPanel implements ActionListener{
	
	private JTextArea queryBox;
	private JButton submitButton;
	private JTextArea result;
	private JButton clearButton;
	
	public AdministratorSqlView(){
		
		queryBox = new JTextArea(10, 90);
		JScrollPane scrollPane = new JScrollPane(queryBox); 
		this.add(scrollPane);
		
		submitButton = new JButton("Submit Query");
		submitButton.addActionListener(this);
		submitButton.setActionCommand("submit");
		this.add(submitButton);
		
		result = new JTextArea(10, 90);
		JScrollPane scrollPane2 = new JScrollPane(result); 
		result.setEditable(false);
		this.add(scrollPane2);
		
		clearButton = new JButton("Clear");
		clearButton.addActionListener(this);
		clearButton.setActionCommand("clear");
		this.add(clearButton);
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getActionCommand() == "submit")
		{
			String query = queryBox.getText();
			
			Connection con = null;
	        Statement stmt = null;
	        try 
			{   //load JDBC driver
				Class.forName("com.mysql.jdbc.Driver");
			    //connect to the DB
				String connectionString = "jdbc:mysql://cs.westga.edu:3307/cmcshan1?user=cmcshan1&password=cm@3274";
	            con = (Connection) DriverManager.getConnection(connectionString);
			    //execute SQL statement
				stmt = (Statement) con.createStatement();
	            ResultSet rs = stmt.executeQuery(query);
	            ResultSetMetaData rsmd = rs.getMetaData();
	            int numberOfColumns = rsmd.getColumnCount();
	            while(rs.next())
	            {
	            	int x = 1;
	            	while(x <= numberOfColumns)
	            	{
	            		result.append(rs.getString(x) + "  ");
	            		x++;
	            	}
	            	result.append("\n");
	            }
	        }
	        catch (Exception exc) 
	        {
	            System.out.println(exc.toString());
	        }
		}
		if(e.getActionCommand() == "clear")
		{
			result.setText("");
		}
	}
		
}
